package com.zzx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.entity.TProductGx;
import com.zzx.mapper.TProductGxMapper;
import com.zzx.service.TProductGxService;
import com.zzx.utils.EntityUtils;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author zzx
 * @description 针对表【t_product_gx(产品-工序表)】的数据库操作Service实现
 * @createDate 2025-06-14
 */
@Service
public class TProductGxServiceImpl extends ServiceImpl<TProductGxMapper, TProductGx>
        implements TProductGxService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TProductGx param) {

        if (ObjectUtils.isEmpty(param.getProductGxId())) {
            param.setProductGxId(IdUtil.getSnowflakeNextId());
        } else {
            TProductGx dbEntity = this.getBaseMapper().selectById(param.getProductGxId());
            if (dbEntity != null) {
                EntityUtils.mergeNonNullProperties(dbEntity, param);
            }
        }
        this.saveOrUpdate(param);
    }

    @Override
    public void addBatch(List<TProductGx> param) {
        if (!ObjectUtils.isEmpty(param)) {
//            LambdaQueryWrapper<TProductGx> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(TProductGx::getCompanyId, UserContext.getCompanyId());
//            wrapper.eq(TProductGx::getProductId, param.get(0).getProductId());
//            wrapper.eq(TProductGx::getProductGxGroupId, param.get(0).getProductGxGroupId());
//            this.remove(wrapper);
            this.saveOrUpdateBatch(param);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TProductGx param) {
        this.removeById(param.getProductGxId());
    }

    @Override
    public IPage<TProductGx> selectBy(TProductGx param) {
        LambdaQueryWrapper<TProductGx> wrapper = new LambdaQueryWrapper<>(TProductGx.class);

        if (!ObjectUtils.isEmpty(param.getProductGxId())) {
            wrapper.eq(TProductGx::getProductGxId, param.getProductGxId());
        }

        // 多租户拦截器会自动添加 company_id 条件
        wrapper.orderByDesc(TProductGx::getCreateTime);

        return this.getBaseMapper().selectPage(
                PageUtils.createPage(param.getPageNum(), param.getPageSize()),
                wrapper
        );
    }

    @Override
    public TProductGx findById(String id) {
        return this.getBaseMapper().selectById(id);
    }
}
